﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Bll;
using Common;
using Web.Extension;
using Microsoft.AspNetCore.Authorization;
using Web.Controllers;
using Web.Filter;

namespace Web.Admin.Controllers
{
    [Route("api/admin/[controller]/[action]")]
    [ApiController]
    [Authorize("admin")]
    [QueryFilter]
    public class UserController : MyBaseController<User>
    {
        IUserBll bll;
        public ITeacherBll teacherBll { get; set; }
        public UserController(IUserBll bll)
        {
            this.bll = bll;
        }
        // GET: api/List/User
        [HttpGet]
        public Result List([FromQuery] Dictionary<string, string> where)
        {
            //return Result.Success("succeed").SetData(bll.SelectAll(o => true, pageNo, pageSize));
            return Result.Success("succeed").SetData(bll.Query(where));
        }

        // GET: api/User/Get/5
        [HttpGet("{id}")]
        public Result Get([FromQuery] Dictionary<string, string> where)
        {
            return Result.Success("succeed").SetData(bll.SelectOne(where));
        }
        // POST: api/User/Add
        [HttpPost]
        public Result Add(User o)
        {
            return ModelState.IsValid ? (bll.Add(o) ? Result.Success("添加成功") : Result.Error("添加失败")) : Result.Error("添加失败!" + ModelState.GetAllErrMsgStr(";")); ;
        }

        // Post: api/User/Update
        [HttpPost]
        public Result Update(User o)
        {
            return ModelState.IsValid ? (bll.Update(o) ? Result.Success("修改成功").SetData(o) : Result.Error("修改失败")) : Result.Error("修改失败!" + ModelState.GetAllErrMsgStr(";")); ;
        }

        // Get: api/User/Delet/5
        [HttpGet("{id}")]
        public Result Delete([FromQuery] Dictionary<string, string> where)
        {
            return bll.Delete(where) ? Result.Success("删除成功") : Result.Error("删除失败");
        }
        [HttpPost]
        public Result BatchDelete([FromForm] Dictionary<string, string> where)
        {
            return bll.Delete(where) ? Result.Success("删除成功") : Result.Error("删除失败");
        }

        [HttpGet]
        public Result ListSchoolAdmin([FromQuery] Dictionary<string, string> where)
        {
            where.Add("role", "admin");
            where.Add("TeacherId__ne", null);
            //return Result.Success("succeed").SetData(bll.SelectAll(o => true, pageNo, pageSize));
            return Result.Success("succeed").SetData(bll.Query(where));
        }
        /// <summary>
        /// 添加学校管理员，即教务管理员
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pswd"></param>
        /// <param name="sn"></param>
        /// <param name="schoolId"></param>
        /// <returns></returns>
        [HttpPost]
        public Result AddSchoolAdmin([FromForm] String username, [FromForm] String realname, [FromForm] String pswd, [FromForm] String sn, [FromForm] int schoolId)
        {
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(realname) || String.IsNullOrEmpty(pswd) || String.IsNullOrEmpty(sn) || schoolId <= 0)
            {
                return Result.Error("添加失败，用户名/真实姓名/密码/工号/学校编号未填写");
            } 
           if(bll.SelectOne(o=>o.Username==username) != null||teacherBll.SelectOne(o => o.Username == username) != null)
            {
                return Result.Error("添加失败，用户名已经存在");
            }
            var u = new User { Username = username, Pswd = pswd, Role = "admin", Realname = realname,SchoolId=schoolId };
            Teacher s = new Teacher();
            s.Username = username;
            s.Role = "teacher";
            s.Pswd = pswd;
            s.Sn = sn;
            s.Timetable_Sn = sn;
            //s.Gender = Gender.man;
            s.Realname = realname;
            /*
            s.Nation = "";
            s.IDCard = "";
            s.Address = "";
            s.Email = "";
            s.Zip = "";
            s.Photo = "";
            s.Tel = "";
            s.Education = "";
            s.Graduate_school = "";
            s.Emergency_number = "";
            s.Credentials = "";*/
            s.SchoolId = schoolId;
            //开启事务
            bll.DbContext().Database.BeginTransaction();
            bool ret = teacherBll.Add(s);
            u.Teacher = s;
            var ret2 = bll.Add(u);
            bll.DbContext().Database.CommitTransaction();//结束事务            
            return Result.Success("添加成功");
        }
        [HttpGet("{id}")]
        public Result DeleteSchoolAdmin(int id)
        {
            User u = bll.SelectOne(id);
            Teacher t = u.Teacher;
            var ret=false;
            bll.DbContext().Database.BeginTransaction();
            if (t != null) {  ret= teacherBll.Delete(t); }
            if (u != null) { ret = bll.Delete(u); }

            bll.DbContext().Database.CommitTransaction();//结束事务                       
            return ret ? Result.Success("删除成功") : Result.Error("删除失败");
        }
        /// <summary>
        /// 修改学校管理员，即教务管理员
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pswd"></param>
        /// <param name="sn"></param>
        /// <param name="schoolId"></param>
        /// <returns></returns>
        [HttpPost]
        public Result UpdateSchoolAdmin([FromForm] int id,[FromForm] String username, [FromForm] String realname, [FromForm] String pswd, [FromForm] String sn, [FromForm] int schoolId)
        {
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(realname) || String.IsNullOrEmpty(pswd) || String.IsNullOrEmpty(sn) || schoolId <= 0)
            {
                return Result.Error("添加失败，用户名/真实姓名/密码/工号/学校编号未填写");
            }
            pswd = Common.Util.Security.Md5(pswd);
            var u = bll.SelectOne(id);
            u.Username = username;
            u.Realname = realname;
            u.Pswd = pswd;
            Teacher s = u.Teacher;
            s.Username = username;
            s.Role = "teacher";
            s.Pswd = pswd;
            s.Sn = sn;
            s.Timetable_Sn =sn;
            //s.Gender = Gender.man;
            s.Realname = realname;
            /*
            s.Nation = "";
            s.IDCard = "";
            s.Address = "";
            s.Email = "";
            s.Zip = "";
            s.Photo = "";
            s.Tel = "";
            s.Education = "";
            s.Graduate_school = "";
            s.Emergency_number = "";
            s.Credentials = "";*/
            s.SchoolId = schoolId;
            //开启事务
            bll.DbContext().Database.BeginTransaction();
            bool ret = teacherBll.Update(s);
            u.Teacher = s;
            var ret2 = bll.Update(u);
            bll.DbContext().Database.CommitTransaction();//结束事务            
            return Result.Success("修改成功");
        }
    }
}
